package com.yanggeng.demo.beginnerguidedemo.widget

import android.graphics.Camera
import android.view.animation.Animation
import android.view.animation.BounceInterpolator
import android.view.animation.Transformation

/**
 * 3D旋转动画
 * @author aiden@tronsis.com
 * @date 2018/9/14 18:08
 */
class Rotate3DAnimation: Animation() {

    private var mCenterWidth = 0
    private var mCenterHeight = 0
    private val mCamera: Camera = Camera()
    private var mRotateY = 20.0f

    override fun initialize(width: Int, height: Int, parentWidth: Int, parentHeight: Int) {
        super.initialize(width, height, parentWidth, parentHeight)
        duration = 4000
        fillAfter = true // 保持动画的结束状态
        interpolator = BounceInterpolator() // 回弹
        mCenterHeight = height / 2
        mCenterWidth = width / 2
    }

    override fun applyTransformation(interpolatedTime: Float, t: Transformation?) {
        super.applyTransformation(interpolatedTime, t)

        val matrix = t?.matrix
        mCamera.save()
        mCamera.rotateY(mRotateY * interpolatedTime)
//        mCamera.rotateX(mRotateY * interpolatedTime)
        mCamera.getMatrix(matrix)
        mCamera.restore()

        matrix?.let {
            it.preTranslate(mCenterWidth.toFloat(), mCenterHeight.toFloat())
            it.postTranslate(-mCenterWidth.toFloat(), -mCenterHeight.toFloat())
        }
    }
}